<template>
  <div ref="helpInfo" :class="{'mobile-help-info':showMobilePage, 'boxShadow': !showMobilePage}" class="help-info">
    <div class="help-info-back" @click="toBack">
      <img :src="back" alt="back">
      <span>返回</span>
    </div>
    <div class="help-info-content">
      <div class="help-info-title">
        <div >{{ dataInfo.title }}</div>
      </div>
      <div class="help-info-time">
        {{ (dataInfo.updateTime / 1000) | standardFormat('YYYY/MM/DD HH:mm:ss') }}
        <span class="help-info-creator">创建人：{{ dataInfo.creator||"管理员" }}</span>
      </div>
      <div v-loading="loading" class="info-content" @click="handleClick" v-html="dataInfo.content"/>
    </div>
    <div v-if="hasRouteAuth('crm:help:edit') || hasRouteAuth('crm:help:del') || isAdmin" id="footer-btn" class="footer-btn">
      <div class="tool-bar-container">
        <el-button v-if="hasRouteAuth('crm:help:edit') || isAdmin" type="primary" size="small" class="submit-btn" @click="toEdit">编辑</el-button>
        <el-button v-if="hasRouteAuth('crm:help:del') || isAdmin" type="danger" plain size="small" class="submit-btn" @click="toDel">删除</el-button>
        <el-button v-if="!showMobilePage" type="info" size="small" class="cancel-btn-style" @click="toBack">返回</el-button>
      </div>
    </div>
    <VueViewer ref="vueviewer" :options="options" :images="srcList" style="display:none;" @inited="inited">
      <img v-for="(src,index) in srcList" :src="src" :key="index">
    </VueViewer>
  </div>
</template>
<script>
import { helpInfo, helpDel } from '@/api/help';
import { standardFormat } from '@/filters/date';
import back from '@/assets/help/back.png';
import downloadIcon from '@/assets/help/download_icon.png';
import leftIcon from '@/assets/help/left_icon.png';
import rightIcon from '@/assets/help/right_icon.png';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
import { component as VueViewer } from 'v-viewer';
import 'viewerjs/dist/viewer.css';

export default {
  filters: { standardFormat },
  components: { VueViewer },
  props: {
    modelName: {
      type: String,
      default: ''
    },
    id: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      back,
      screenHeight: null,
      dataInfo: {},
      clientWidth: null,
      infoHeight: null,
      loading: false,
      srcList: [], // 文章中所有的图片路径
      currentIndex: 0, // 文章中点击的图片index
      options: {
        title: false,
        navbar: false,
        toolbar: {
          zoomIn: 1,
          zoomOut: 1,
          oneToOne: 1,
          reset: 0,
          prev: {
            show: 4,
            size: 'large'
          },
          play: 0,
          next: {
            show: 4,
            size: 'large'
          },
          rotateLeft: 1,
          rotateRight: 1,
          flipHorizontal: 0,
          flipVertical: 0
        },
        initialViewIndex: this.currentIndex
      }
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    }
  },
  created() {
    this.getInfo();
  },
  methods: {
    hasRouteAuth,
    inited(viewer) {
      this.$viewer = viewer;
    },
    getInfo() {
      this.loading = true;
      helpInfo(this.id).then(res => {
        this.loading = false;
        this.dataInfo = res.data;
        this.handleMatchImgList();
      }).catch(err => {
        this.loading = false;
        console.error(err);
        this.$router.push({
          name: 'help',
          query: {
            model: this.modelName
          }
        });
      });
    },
    toBack() {
      this.$emit('toBack');
    },
    toEdit() {
      this.$router.push({
        name: 'helpEdit',
        params: { id: this.id }
      });
    },
    toDel() {
      this.$confirm('确定删除该文章？', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        center: true,
        type: 'warning',
        customClass: 'del-message del-message-cancel',
        iconClass: 'del-icon'
      }).then(() => {
        helpDel(this.id).then(res => {
          this.$message.success('删除成功');
          this.$router.push({
            name: 'help',
            query: {
              model: this.modelName
            }
          });
        }).catch(err => {
          console.error(err);
        });
      }).catch(() => {});
    },
    handleClick(e) {
      if (e.target.nodeName === 'IMG') {
        const currentSrc = e.target.currentSrc;
        currentSrc && (this.currentIndex = this.srcList.findIndex(item => {
          return item === currentSrc;
        }));
        this.$viewer.view(this.currentIndex);
        this.modifyToolbarStyle();
        this.insertDownloadBtn();
      }
    },
    // 匹配出文章字符串中的所有图片路径
    handleMatchImgList() {
      // const reg = /<img.*?(?:>|\/>)/gi;
      // const imgList = this.dataInfo.content.match(reg);
      const src = /src=[\'\"]?([^\'\"]*)[\'\"]?/gi;
      this.srcList = this.dataInfo.content.match(src);
      if (this.srcList && this.srcList.length > 0) {
        this.srcList = this.srcList.map(item => {
          item = item.replace(/src=|\"/g, '');
          item = item.replace(/&#x2F;/g, '/'); // 将&#x2F;替换为/
          return item;
        });
      } else {
        this.srcList = [];
      }
    },
    modifyToolbarStyle() {
      // 设置切换上下张图标位置
      const prev = document.getElementsByClassName('viewer-prev')[0];
      const next = document.getElementsByClassName('viewer-next')[0];
      prev.setAttribute('style', 'position:fixed;left:10px;top:50%;');
      next.setAttribute('style', 'position:fixed;right:10px;top:50%;');
      // 修改左右旋转图标
      document.styleSheets[0].insertRule(`.viewer-rotate-left::before{display:none !important;}`, 0);
      document.styleSheets[0].insertRule(`.viewer-rotate-right::before{display:none !important;}`, 0);
      const leftEle = document.getElementsByClassName('viewer-rotate-left')[0];
      const rightEle = document.getElementsByClassName('viewer-rotate-right')[0];
      leftEle.innerHTML = `<img src="${leftIcon}" style="width:12px;height:12px;margin:6px;"/>`;
      rightEle.innerHTML = `<img src="${rightIcon}" style="width:12px;height:12px;margin:6px;"/>`;
    },
    // 插入下载按钮
    insertDownloadBtn() {
      const ele = document.getElementsByClassName('viewer-toolbar')[0].children[0];
      const downloadElement = document.createElement('li');
      downloadElement.innerHTML = `<img src="${downloadIcon}" style="width:12px;height:12px;margin:6px;"/>`;
      downloadElement.addEventListener('click', () => {
        // 获取当前预览的图片路径
        const viewImg = document.getElementsByClassName('viewer-canvas')[0].children[0];
        const url = viewImg.src;
        this.downloadImage(url, '下载图片');
      });
      ele.appendChild(downloadElement);
    },
    // 下载图片
    downloadImage(imgsrc, name) {
      const image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute('crossOrigin', 'anonymous');
      image.onload = () => {
        const canvas = document.createElement('canvas');
        canvas.width = image.width;
        canvas.height = image.height;
        const context = canvas.getContext('2d');
        context.drawImage(image, 0, 0, image.width, image.height);
        const url = canvas.toDataURL('image/png'); // 得到图片的base64编码数据
        const a = document.createElement('a');
        const event = new MouseEvent('click'); // 创建单击事件
        a.download = name || 'photo';
        a.href = url;
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = imgsrc;
    }
  }
};
</script>
<style lang="scss" scope>
.help-info {
  position: relative;
  width: 100%;
  margin: 16px 16px 74px 225px;
  background: #FFFFFF;
  opacity: 1;
  border-radius: 4px;
  padding-top: 82px;
  overflow-x: hidden;
  box-sizing: border-box;
  &.boxShadow {
    box-shadow: 2px 4px 10px #DDE1EA;
  }
  .help-info-back {
    padding: 0 24px;
    display: flex;
    align-items: center;
    font-size: 14px;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 20px;
    color: #333333;
    cursor: pointer;
    img {
      width: 14px;
      height: auto;
    }
  }
  .help-info-content {
    margin-top: 22px;
    padding: 0 24px;
    min-height: calc(100vh - 410px);
    .help-info-title {
      font-size: 20px;
      font-family: PingFang SC;
      font-weight: 500;
      color: #333333;
      word-break: break-all;
      width: 100%;
    }
    .help-info-time {
      margin-top: 12px;
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 400;
      color: #999999;
      .help-info-creator{
        margin-left:10px
      }
    }
    .info-content {
      //   overflow-y: auto;
      margin-top: 24px;
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 400;
      line-height: 24px;
      color: #333333;
      table {
          border-spacing: 0;
          border-collapse: collapse;
          width: 100%;
      }
      td, th {
        border-width: 1px;
        border-style: solid;
      }
      .tb-table td, th {
        border-color: #aaa;
      }
      [textbus-editable=on] {
        user-select: text;
        cursor: text;
      }
      p {
        word-break: break-all;
      }
      h1, h2, h3, h4 { // 标题样式
        line-height: 1.5;
      }
    }
  }
  .footer-btn {
    width: 100%;
  }
  .tool-bar-container {
    position: fixed;
    right: 0;
    bottom: 0;
    height: 56px;
    width: 100%;
    z-index: 100;
    background: #fff;

    width: 100%;
    display:flex;
    justify-content: center;
    align-items: center;
    border-top: 1px solid #ddd;
    &::v-deep {
      .el-button {
        height: 32px;
        margin-left: 16px;
      }
    }
  }
}
.mobile-help-info {
  margin: 0;
  padding-top: 12px;
  .help-info-back {
    padding: 0 12px;
  }
  .help-info-content {
    margin: 12px 0 56px;
    padding: 0 12px;
  }
}
</style>
